-- CLIENT FUNCTIONS
local __enumID=0; function enum( names )
   local t={}
   for _,k in ipairs(names) do
     t[k]=__enumID
     __enumID = __enumID+1
   end
   return t
end

-- What debug output is included at a set level?
--           /----------------------------\
--           | DEBUG | INFO | WARN | CRIT |
-- Set level |-------+------+------+------|
-- DEBUG     |  Y    |  Y   |  Y   |  Y   |
-- INFO      |       |  Y   |  Y   |  Y   |
-- WARN      |       |      |  Y   |  Y   |
-- CRIT      |       |      |      |  Y   |
--           \----------------------------/
debugLevels = enum{'INFO','WARN','CRIT','DEBUG'}
debug = debugLevels.DEBUG -- by default

-- TODO: Load this from a file on local disk
-- Target console ID
masterID=33

function setDebug()
	debug = debugLevels.DEBUG
end

function setCritical()
	debug = debugLevels.CRIT
end

function setWarning()
	debug = debugLevels.WARN
end

function setInfo()
	debug = debugLevels.DEBUG
end

function getDebugLevel()
	return debug
end

-- Send a message packet via rednet to the base station (monitoring console) - message text is optional, if you want to just send a status update
function xmit(text)
	local x,y,z = brum.getCurrentPos()
	local statMessage = {"LOGGERAPI",
											 ["id"]=os.getComputerID(),
											 ["range"]=turtle.getFuelLevel(),
											 ["fuel"]=turtle.getItemCount(1),
											 ["status"]=brum.getStatus(),
											 ["x"]=x, ["y"]=y, ["z"]=z,
											 ["inventory"]=brum.stockTake(),
											 ["freeslots"]=brum.numEmptySlots(),
											 ["msg"]=text
											}
	if not rednet.send(masterID,textutils.serialize(statMessage)) then
		print("WARN: Failed to perform rednet.send()")
		return false
	else
		return true
	end
end

-- Logs a message at debug level
function debug(text)
	local msg = tostring(text)
	print(msg) -- print all debug messages to turtles local terminal
	local xfile=io.open("/log.txt","w")
	xfile:write(text)
	xfile:close()

	-- Only transmit if we're at debug level or higher
	if debug==debugLevels.DEBUG then
		xmit("DEBUG:"..msg)
	end
end

-- Logs a message at info level
function info(text)
	local msg = tostring(text)
	-- Only transmit if we're at info level or higher
	if (debug==debugLevels.DEBUG) or (debug==debugLevels.INFO) then
		print(msg) -- to local terminal
		xmit("INFO:"..msg) -- to rednet
	end
end

-- Logs a message at warn level
function warn(text)
	local msg = tostring(text)
	-- Only transmit if we're at warn level or higher
	if (debug==debugLevels.DEBUG) or (debug==debugLevels.INFO) or (debug==debugLevels.WARN) then
		print(msg) -- to local terminal
		xmit("WARN:"..msg) -- to rednet
	end
end

-- Logs a message at critical level
function crit(text)
	local msg = tostring(text)
	-- Critical is ALWAYS transmitted and displayed...
	print(msg) -- to local terminal
	xmit("CRIT:"..msg) -- to rednet
end
